package src.controller;

import java.rmi.RemoteException;

import src.resource.DialogResource;
import src.resource.ValidateResource;
import src.resource.DialogResource.windowTypeEnum;
import src.service.ClientService;
import src.view.AddUser;

public class AddUserController {
	
	private ClientService system;
	private AddUser view;
	
	public AddUserController(ClientService system){
		this.view=AddUser.getInstance(this);
		this.system=system;
		
	}
	
	public void performSaveUser() throws RemoteException{
		if(!validateRequiredFields()){
			DialogResource.showMessage(view.getBtnSave().getLocationOnScreen(),"Information","Must complete the required fields.",windowTypeEnum.wtInformation);
			return;
		}
		if(!validateFieldsLenght()){
			DialogResource.showMessage(view.getBtnSave().getLocationOnScreen(),"Information","The fields can not contain more than 50 characters.",windowTypeEnum.wtInformation);
			return;
		}
		
		if(system.getUserByUserName(view.getTxtName().getText())!=null){
			DialogResource.showMessage(view.getBtnSave().getLocationOnScreen(),"Information","User name in use. Please enter another user name.",windowTypeEnum.wtInformation);
			return;
		}
			
		
		system.saveUser(view.getTxtName().getText(),view.getTxtUserName().getText(), view.getTxtCountry().getText(),view.getTxtCity().getText(), 
				view.getTxtAddress().getText(),view.getTxtPhoneNumber().getText(),view.getChkActive().isSelected());
		DialogResource.showMessage(view.getBtnSave().getLocation(),"Information","User saved sucessfully.",windowTypeEnum.wtConfirmation);
		this.cleanForm();
	}
	
	private void cleanForm(){
		view.getTxtName().setText("");
		view.getTxtUserName().setText("");
		view.getTxtCountry().setText("");
		view.getTxtCity().setText("");
		view.getTxtAddress().setText("");
		view.getTxtPhoneNumber().setText("");
		view.getChkActive().setSelected(false);
	}
	
	private boolean validateRequiredFields(){
		return ValidateResource.validateRequiredField(view.getTxtName().getText()) && ValidateResource.validateRequiredField(view.getTxtUserName().getText());
	}
	
	private boolean validateFieldsLenght(){
		return ValidateResource.validateStringLength(view.getTxtName().getText(), 50) && ValidateResource.validateStringLength(view.getTxtUserName().getText(), 50)
		&& ValidateResource.validateStringLength(view.getTxtCountry().getText(), 50) && ValidateResource.validateStringLength(view.getTxtCity().getText(), 50)
		&&ValidateResource.validateStringLength(view.getTxtAddress().getText(), 50)&& ValidateResource.validateStringLength(view.getTxtPhoneNumber().getText(), 50);
	}

}
